let contextPath = '';
let systemLib = new SystemLib();
function SystemLib() {
}

SystemLib.prototype.getDataGridChecks = function(rows){
    let arr = [];
    if(rows){
        $.each(rows, function (index, o) {
            arr.push(o.id);
        });
    }
    return arr;
};

SystemLib.prototype.createUser = function() {
    $('#dlg_user').dialog({title:'新增用户'}).dialog('open').dialog('center');
    $('#form_user').form('clear');
    $('#form_user_username').textbox({readonly:false});
    $('#form_user_password').passwordbox({required:true});
    $('#form_user_confirmPassword').passwordbox({required:true});
};

SystemLib.prototype.updateUser = function() {
    let row = $('#dg_user').datagrid('getSelected');
    if(row){
        if(row.username==='admin'){
            layer.alert('admin用户不可修改！');
            return;
        }
        $('#dlg_user').dialog({title:'修改用户信息'}).dialog('open').dialog('center');
        let userform = $('#form_user');
        userform.form('clear');
        userform.form('load', row);
        $('#form_user_username').textbox({readonly:true});
        $('#form_user_password').passwordbox({required:false});
        $('#form_user_confirmPassword').passwordbox({required:false});
    }else{
        layer.alert('请选择数据！');
    }
};

SystemLib.prototype.saveUser = function() {
    let form_id =  $('#form_user_id').val();
    let url = contextPath + "/auth/user";
    if(form_id===""){
        url+="/create";
    }else{
        url+="/update";
    }
    let loadLayer;
    $('#form_user').form('submit',{
        url: url,
        onSubmit: function(){
            let isValid = $(this).form('validate');
            if (isValid){
                loadLayer = layer.load(1, {shade: [0.1,'#000']});
            }
            return isValid;
        },
        success: function(result){
            layer.close(loadLayer);
            let data = JSON.parse(result);
            if (data.status === 1){
                layer.alert('保存成功！');
                $('#dg_user').datagrid('reload');
                $('#dlg_user').dialog('close');
            } else {
                layer.alert('保存失败：' + data.errorMsg);
            }
        }
    });
};

SystemLib.prototype.deleteUser = function() {
    let row = $('#dg_user').datagrid('getSelected');
    if(row){
        let ly = layer.confirm('确定要删除吗？', {
            btn: ['确定','取消'] //按钮
        },function () {
            let data = {id:row.id, userId:row.userId};
            $.post(contextPath + '/auth/user/delete', data, function (result) {
                layer.close(ly);
                if(result.status===1){
                    $('#dg_user').datagrid('reload');
                }else{
                    layer.alert(result.errorMsg);
                }
            },'json');
        });
    }else{
        layer.alert('请选择数据！');
    }
};

SystemLib.prototype.searchAggregate = function () {
    let queryJson = $('#qm_aggregate').serializeJSON();
    $('#dg_aggregate').datagrid('load', queryJson);
};

SystemLib.prototype.findAggregateDetail = function () {

};

SystemLib.prototype.deleteAggregate = function () {
    let that = this;
    let rows = $('#dg_aggregate').datagrid('getChecked');
    if(rows && rows.length>0){
        let ly = layer.confirm('确定要删除吗？', {
            btn: ['确定','取消']
        },function () {
            let idArr = that.getDataGridChecks(rows);
            let data = {ids:idArr.join(',')};
            $.post(contextPath + '/auth/report/deleteAggregate', data, function (result) {
                layer.close(ly);
                if(result.status===1){
                    $('#dg_aggregate').datagrid('reload');
                }else{
                    layer.alert(result.errorMsg);
                }
            },'json');
        });
    }else{
        layer.alert('请选择数据！');
    }
};

SystemLib.prototype.searchSampler = function () {
    let queryJson = $('#qm_sampler').serializeJSON();
    $('#dg_sampler').datagrid('load', queryJson);
};

SystemLib.prototype.findSamplerDetail = function () {
    let rows = $('#dg_sampler').datagrid('getChecked');
    if(rows && rows.length>0){
        this.viewSamplerDetail(rows[0])
    }
};

SystemLib.prototype.viewSamplerDetail = function(row){
    let sampleResult = $('#history_sample_result');
    sampleResult.empty();
    let sampleRequest = $('#history_sample_request_header');
    sampleRequest.empty();
    let sampleResponse = $('#history_sample_response');
    sampleResponse.empty();
    $('#dlg_sampler').dialog({title:'查看采样数据'}).dialog('open').dialog('center');
    historySamplerTree.buildTree($('#history_sampler_tree'), row.planId, row.testId, row.threadId);
};

SystemLib.prototype.showSampleResult = function(sample, eid) {
    let sampleResult = $('#history_sample_result');
    sampleResult.empty();
    let sampleRequest = $('#history_sample_request_header');
    sampleRequest.empty();
    let sampleResponse = $('#history_sample_response');
    sampleResponse.empty();
    if(sample===undefined || sample.category===undefined){
        return;
    }

    let sb = new StringBuilder();
    if(sample.category.lastIndexOf('Assertion')>=0){
        sb.append("Assertion error：" + sample.assertionError + "<br/>");
        sb.append("Assertion failure：" + sample.assertionFailure + "<br/>");
        sb.append("Assertion failure message：" + sample.assertionMessage + "<br/>");
        sampleResult.html(sb.toString());
    }else{
        sb.append("threadName：" + sample.threadName + "<br/>");
        sb.append("startTime：" + sample.startTimeFmt + "<br/>");
        sb.append("endTime：" + sample.endTimeFmt + "<br/>");
        sb.append("connectTime：" + sample.connectTime + "<br/>");
        sb.append("latency：" + sample.latency + "<br/>");
        sb.append("elapsedTime：" + sample.elapsedTime + "<br/>");
        sb.append("sentBytes：" + sample.sentBytes + "<br/>");
        sb.append("headersSize：" + sample.headersSize + "<br/>");
        sb.append("responseCode：" + sample.responseCode + "<br/>");
        if(sample.dataType==='json'){
            sb.append("responseMessage：" + sample.responseMessage + "<br/>");
        }else{
            sb.append("responseMessage：" + sample.responseMessage.replaceAll('\n', '<br/>') + "<br/>");
        }
        sb.append("sampleCount：" + sample.sampleCount + "<br/>");
        sb.append("samplerData：" + sample.samplerData.replaceAll('\n', '<br/>') + "<br/>");
        sampleResult.html(sb.toString());

        sampleRequest.html(sample.requestHeaders.replaceAll('\n', '<br/>'));
        if(sample.dataType==='json'){
            sampleResponse.text(sample.responseData);
        }else{
            sampleResponse.html(sample.responseData.replaceAll('\n', '<br/>'));
        }
    }
};

SystemLib.prototype.deleteSampler = function () {
    let that = this;
    let rows = $('#dg_sampler').datagrid('getChecked');
    if(rows && rows.length>0){
        let ly = layer.confirm('确定要删除吗？', {
            btn: ['确定','取消']
        },function () {
            let idArr = that.getDataGridChecks(rows);
            let data = {ids:idArr.join(',')};
            $.post(contextPath + '/auth/report/deleteSampler', data, function (result) {
                layer.close(ly);
                if(result.status===1){
                    $('#dg_sampler').datagrid('reload');
                }else{
                    layer.alert(result.errorMsg);
                }
            },'json');
        });
    }else{
        layer.alert('请选择数据！');
    }
};